//在后续的wps版本中，wps的所有枚举值都会通过wps.Enum对象来自动支持，现阶段先人工定义
var WPS_Enum = {
    msoCTPDockPositionLeft: 0,
    msoCTPDockPositionRight: 2
}

function GetUrlPath() {
    let e = document.location.toString()
    return -1 != (e = decodeURI(e)).indexOf("/") && (e = e.substring(0, e.lastIndexOf("/"))), e
}
/**
 * 通过wps提供的接口执行一段脚本
 * @param {*} param 需要执行的脚本
 */
function shellExecuteByOAAssist(param) {
    if (wps != null) {
        wps.OAAssist.ShellExecute(param)
    }
}

/**
 * Taskpane 切换
 * @param {string} contrlId 控件ID
 * @param {string} taskpanePage Taskpane页面路径
 */
function taskpaneToggle(contrlId, taskpanePage) {
    let tsId = wps.PluginStorage.getItem(contrlId)
    if (!tsId) {
        let tskpane = wps.CreateTaskPane(GetUrlPath() + taskpanePage)
        let id = tskpane.ID
        wps.PluginStorage.setItem(contrlId, id)
        tskpane.Visible = true
    } else {
        let tskpane = wps.GetTaskPane(tsId)
        tskpane.Visible = !tskpane.Visible
    }
}

const uuid = wps.Application.ProductCode.replace(/[}|{]/g, "");

/**
 * 获取当前激活工作簿的所有工作表信息
 * @returns {Object}
 */
function getShs() {
    let wb = wps.Application.ActiveWorkbook;
    let wb_shs = wb.Worksheets.Count;
    let shs_names_visible = []
    let shs_names_unvisible = []

    for (let i = 1; i <= wb_shs; i++) {
        let item = wb.Worksheets.Item(i);
        if (!item.Visble) {
            shs_names_visible.push(item.Name)
        } else {
            shs_names_unvisible.push(item.Name)
        }
    }
    return {
        shs: wb.Sheets,
        all: [shs_names_visible, shs_names_unvisible].flat(),
        visible: shs_names_visible,
        unvisible: shs_names_unvisible,
    }
}

/**
 * 删除 TaskPane ，主要用来控制需要关闭即删除的 TaskPane（不需要在后台驻留的 TaskPane）
 * 
 * @param {string} key TaskPane 创建时注册的 PluginStorage key.
 */
function taskpaneDelete(key){
    let tpId = Application.PluginStorage.getItem(key)
    let tp = Application.GetTaskPane(tpId)
    if(!tp.Visible){
        tp.Delete()
        // 清除 key，否则无法再次创建这个 TaskPane
        Application.PluginStorage.removeItem(key) 
        // setItem(key, null) //这样也可以
    }
}

// 监视 TaskPane 隐藏事件
Application.ApiEvent.AddApiEventListener('AfterTaskPaneHidden',()=>{
    taskpaneDelete('summary') // 目录
})